<?php

/**
 * 登录
 * 
 * @author ShuangYa
 * @package TBSign
 * @category Controller
 * @link http://www.sylingd.com/
 */

namespace tbsign\controller;
use \Sy;
use \sy\base\Controller;
use \sy\lib\YCookie;
use \sy\lib\YFetchURL;

class Login extends Controller {
	public function __construct() {
	}
	/**
	 * Hello页面
	 */
	public function actionHello() {
		Sy::view('login/hello');
	}
	/**
	 * 跳转到百度OAuth
	 */
	public function actionGoBaidu() {
		$go = 'https://openapi.baidu.com/oauth/2.0/authorize?' . http_build_query(['response_type' => 'code', 'client_id' => Sy::$app['BaiduOAuth']['client_id'], 'redirect_uri' => Sy::createUrl('login/oauthBaidu')]);
		header('Location: ' . $go);
	}
	/**
	 * OAuth回调
	 */
	public function actionOauthBaidu() {
		$code = $_GET['code'];
		if (empty($code)) {
			echo '参数错误';
			exit;
		}
		//获取Access token
		$access_token = json_decode(YFetchURL::i([
			'url' => 'https://openapi.baidu.com/oauth/2.0/token?' . http_build_query([
				'grant_type' => 'authorization_code',
				'code' => $code,
				'client_id' => Sy::$app['BaiduOAuth']['client_id'],
				'client_secret' =>  Sy::$app['BaiduOAuth']['client_secret'],
				'redirect_uri' => Sy::createUrl('login/oauthBaidu')
			]),
			'header' => 0
		])->exec(), 1);
		if (!isset($access_token['access_token'])) {
			if (isset($oauthinfo['error_description'])) {
				echo $oauthinfo['error_description'];
				exit;
			} else {
				echo 'OAuth授权失败';
				exit;
			}
		}
		//获取用户信息
		$userinfo = json_decode(YFetchURL::i([
			'url' => 'https://openapi.baidu.com/rest/2.0/passport/users/getLoggedInUser?' . http_build_query([
				'access_token' => $access_token['access_token'],
				'format' => 'json'
			]),
			'header' => 0
		])->exec(), 1);
		//检查是否允许
		if (!in_array($userinfo['uname'], Sy::$app['sign']['allow'], TRUE)) {
			echo '很抱歉，您没有使用资格。如有疑问，请与站长联系';
			exit;
		}
		//登录标记
		YCookie::sSet(2, ['name' => 'access_token', 'value' => $access_token['access_token'], 'httponly' => TRUE]);
		echo '登录成功';
		echo '<script>window.location.href="', Sy::createUrl('setting/sign'), '";</script>';
	}
}
